package com.study.jdk.j8;

import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author: jzhou
 * @date: 2024/12/1-16:41
 * @version: 1.0
 * @description: juc-study
 */
@State(Scope.Thread)
public class ForBenchmark {
    private List<Integer> ids ;
    @Setup
    public void setup() {
        ids = new ArrayList<>();
        //分别对10、100、1000、1万、10万个元素测试
        IntStream.range(0, 10000).forEach(i -> ids.add(i));
    }
    @TearDown
    public void tearDown() {
        ids = new ArrayList<>();
    }
    @Benchmark
    public void testFor() {
        for (int i = 0; i <ids.size() ; i++) {
            Integer id = ids.get(i);
        }
    }

    @Benchmark
    public void testStreamforEach() {
        ids.stream().forEach(x->{
            Integer id=x;
        });
    }

    @Test
    public void testMyBenchmark() throws Exception {
        Options options = new OptionsBuilder()
                .include(ForBenchmark.class.getSimpleName())
                .forks(1)
                .threads(1)
                .warmupIterations(1)
                .measurementIterations(1)
                .mode(Mode.Throughput)
                .build();
        new Runner(options).run();
    }


    @Test
    public void testForGc() {
        List<Integer> ids = IntStream.range(1,10000000).boxed().collect(Collectors.toList());
        int sum = 0;
        for (int i = 0; i < ids.size(); i++) {
            sum +=ids.get(i);
        }
        System.gc();
    }

    @Test
    public void testStreamGc() {
        List<Integer> ids = IntStream.range(1,10000000).boxed().collect(Collectors.toList());
        int sum = ids.stream().mapToInt(x->x).sum();
//        int sum_1 = ids.stream().reduce(0,Integer::sum);
        System.gc();
    }
}
